<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */
namespace MoChat\Plugin\WorkMoment\Action\Workbench;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use Hyperf\Utils\Codec\Json;
use MoChat\App\Common\Middleware\WorkbenchAuthMiddleware;
use MoChat\App\WorkEmployee\Contract\WorkEmployeeContract;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;
use MoChat\Plugin\WorkMoment\Contract\WorkMomentContract;

/**
 * 企微朋友圈-列表.
 *
 * Class Index.
 * @Controller
 */
class Index extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var WorkEmployeeContract
     */
    protected $workEmployeeContract;

    /**
     * @Inject
     * @var WorkMomentContract
     */
    private $workMomentContract;

    /**
     * @Middlewares({
     *     @Middleware(WorkbenchAuthMiddleware::class)
     * })
     * @RequestMapping(path="/workbench/workMoment/index", methods="get")
     * @return array 返回数组
     */
    public function handle(): array
    {
        $user = user();
        // 判断用户绑定企业信息
        if (! isset($user['corpId'])) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '未选择登录企业，不可操作');
        }
        // 接收参数
        $params = [
            'page' => (int) $this->request->input('page', 1),
            'perPage' => (int) $this->request->input('perPage', 10),
            'searchText' => $this->request->input('searchText', ''),
        ];
        $params['corpId'] = $user['corpId'];
        $params['employeeId'] = $user['id'];

        // 校验参数
        $this->validated($params);

        // 组织查询条件
        $where['corp_id'] = $params['corpId'];
        $where['create_type'] = 1;
        $where['creator'] = $user['wxUserId'];
        if (! empty($params['searchText'])) {
            $where[] = ['text->content', 'like', '%' . $params['searchText'] . '%'];
        }
        $options = [
            'page' => $params['page'],
            'perPage' => $params['perPage'],
            'orderByRaw' => 'id desc',
        ];
        $columns = ['id', 'employee_id', 'create_type', 'create_time', 'text', 'image', 'video', 'link'];
        $res = $this->workMomentContract->getWorkMomentList($where, $columns, $options);
        // 组织响应数据
        $data = [
            'page' => [
                'perPage' => $params['perPage'],
                'total' => 0,
                'totalPage' => 0,
            ],
            'list' => [],
        ];

        if (empty($res['data'])) {
            return $data;
        }
        // 处理分页数据
        $data['page']['total'] = $res['total'];
        $data['page']['totalPage'] = $res['last_page'];
        $data['list'] = $this->handleData($res['data']);
        return $data;
    }

    /**
     * 验证规则.
     *
     * @return array 响应数据
     */
    protected function rules(): array
    {
        return [
        ];
    }

    /**
     * 验证错误提示.
     * @return array 响应数据
     */
    protected function messages(): array
    {
        return [
        ];
    }

    private function handleData(array $list): array
    {
        foreach ($list as $k => $v) {
            $list[$k]['createTime'] = date('m-d H:i', (int) $v['createTime']);
            // 文字
            if (! empty(Json::decode($v['text']))) {
                $list[$k]['contentType'] = '文字';
                $list[$k]['text'] = Json::decode($v['text']);
            }
            // 图片
            if (! empty(Json::decode($v['image']))) {
                $list[$k]['contentType'] = '图片';
                $images = Json::decode($v['image']);
                foreach ($images as $imageKey => $imageVal) {
                    $images[$imageKey]['image'] = file_full_url($imageVal['image']);
                }
                $list[$k]['image'] = $images;
            }
            // 视频
            if (! empty(Json::decode($v['video']))) {
                $list[$k]['contentType'] = '视频';
                $video = Json::decode($v['video']);
                $list[$k]['video'] = file_full_url($video['video']);
            }
            // 链接
            if (! empty(Json::decode($v['link']))) {
                $list[$k]['contentType'] = '链接';
                $list[$k]['link'] = Json::decode($v['link']);
            }
            // 创建人
            $creator = $this->workEmployeeContract->getWorkEmployeeById($v['employeeId'], ['name']);
            $list[$k]['creator'] = $creator['name'] ?? '';
        }
        return $list;
    }
}
